package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {
    /***
     * 获取静态资源文件的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        absolutePath= absolutePath.replaceAll("\\\\","/")+path;
        return absolutePath;
    }

    /***
     * 读取静态资源文件输入流。通过输出流输出
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count=0;
        while (count==0){
            count=inputStream.available();
        }
        int resourSize=count;
        //hhtp请求头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourSize).getBytes());
        //读取内容输出
        long written =0; //已经读取的内容长度
        int byteSize=1024;//计划每次缓冲的长度
        byte[] bytes = new byte[byteSize];
        while (written<resourSize){//进来的数据还没写完
            if(written + byteSize >resourSize ){
                //剩下没处理的内容只需要一个字节数组就可以装完,就按真实的内容长度的定义数组
                byteSize= (int) (resourSize-written);//剩余的文件内容产长度
                bytes= new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written+=byteSize;
        }

    }


}


